package HashMapSeries;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GroupAnagramsSolution_hot100_49 {
    public List<List<String>> groupAnagrams(String[] strs) {
        //对每个字符串计数得到该字符串的计数数组，对于计数数组相同的字符串，就互为异位词
        // key = 'a1e1t1'
        // value = ['eat', 'tea', 'ate']
        Map<String, List<String>> map = new HashMap<String, List<String>>();

        for (String str : strs) {
            // 首先遍历字符串str，将其每一个字符对应出现的次数变成字符数组
            int[] counts = new int[26];
            int len = str.length();
            for (int i = 0; i < len; i++) {
                counts[str.charAt(i) - 'a'] += 1;
            }

            // 变成我们要的字符信息字符串"a3b2c1"
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < 26; i++) {
                if (counts[i] != 0) {
                    sb.append((char) ('a' + i)); //'b'
                    sb.append(counts[i]); // '2'
                }
            }

            String key = sb.toString();
            List<String> list = map.getOrDefault(key, new ArrayList<String>());
            list.add(str);
            map.put(key, list);
        }

        return new ArrayList<List<String>>(map.values());
    }
}
